package com.terren.spider.util.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.log4j.Logger;

public class RandomProxy {
	private static Logger logger = Logger.getLogger(RandomUA.class.getName());
	private static ArrayList<String> proxyList = new ArrayList<String>();
	private static boolean loadProxy = false;
	
	public static String getRandomProxy() {
		if(!loadProxy)
			proxyList = importProxy();
		int n = (int)Math.floor(Math.random() * proxyList.size());
		int i = 0;
		String randomProxy = null;
		for(String proxy : proxyList) {
			if(i == n) {
				randomProxy = proxy;
				break;
			}
			i++;
		}
		return randomProxy;
	}
	
	private static ArrayList<String> importProxy(){
		ArrayList<String> proxyLs = new ArrayList<String>();
		try{
			File file = new File("./Data/proxy.txt");
	    	InputStreamReader fr = new InputStreamReader( new FileInputStream(file),"GBK"); 
			BufferedReader br = new BufferedReader(fr);
			String str = br.readLine();
			while(str != null && str.length() > 0) {
				proxyLs.add(str);
				str = br.readLine();
			}
			br.close();
			fr.close();
			loadProxy = true;
			logger.info("Reading " + proxyLs.size() + " Proxy.");
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return proxyLs;
	}
	
	public static int eraseProxy(String badProxy) {
		proxyList.remove(badProxy);
		logger.debug("Size of proxy list: "+ proxyList.size());
		return proxyList.size();
	}
	
	public static void showProxys() {
		logger.debug("Valid proxy: ");
		for(String proxy : proxyList)
			logger.debug(proxy);
	}
}
